﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Drawing.Drawing2D;

namespace Taxes.KML
{
    public class Region
    {
        public string ID
        {
            get;
            set;
        }
        public string Name
        {
            get;
            set;
        }
        public string Postion
        {
            get;
            set;
        }
        public float Cost
        {
            get;
            set;
        }

        public static void Insert(List<Region> regions)
        {
            
        }

        public static void ConvertPostion(string postion, out List<double> lons, out List<double> lats)
        {
            string[] cood = postion.Split(' ');
            lons = new List<double>(cood.Length);
            lats = new List<double>(cood.Length);

            foreach (var s in cood)
            {
                string[] array = s.Split(',');
                double lon;
                double lat;
                double.TryParse(array[0], out lon);
                double.TryParse(array[1], out lat);
                lons.Add(lon);
                lats.Add(lat);
            }
        }
        public static bool IsInRegion(double lon, double lat,Region region)
        {
            int wn = 0, j = 0;
            for (int i = 0; i < region.Lons.Count; i++)
            {
                if (i == region.Lons.Count - 1)
                {
                    j = 0;
                }
                else
                {
                    j++;
                }
                if (region.Lats[i] <= lat)
                {
                    if (region.Lats[j] > lat)
                    {
                        if (IsLeft(region.Lons[i], region.Lats[i], region.Lons[j], region.Lats[j], lon, lat) > 0)
                        {
                            wn++;
                        }
                    }
                }
                else
                {
                    if (region.Lats[j] <= lat)
                    {
                        if (IsLeft(region.Lons[i], region.Lats[i], region.Lons[j], region.Lats[j], lon, lat) < 0)
                        {
                            wn--;
                        }
                    }
                }
            }
            return wn != 0;
        }
        private static double IsLeft(double lon0, double lat0, double lon1, double lat1, double lon2, double lat2)
        {
            double abc = (lon1 - lon0) * (lat2 - lat0) - (lon2 - lon0) * (lat1 - lat0);
            return abc;
        }

        


        public List<double> Lons
        {
            get;
            set;
        }

        public List<double> Lats
        {
            get;
            set;
        }
    }
}